import { useState, useEffect, useMemo } from 'react'
import { useWatcher } from 'alova/client'
import { createAlovaMethod } from '@/apis/ApiRequest'
import { toast } from 'sonner'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Loading } from '@/components/ui/loading'
import { Empty } from '@/components/ui/empty'
import { Button } from '@/components/ui/button'
import SearchBar from './components/SearchBar'
import MusicList from './components/MusicList'

import type { MusicStoreRecord } from '@/types/music'

const api: ApiConfig = {
  url: 'https://music-api.gdstudio.xyz/api.php',
  method: 'GET',
  description: '获取音乐列表',
  proxyPrefix: '',
}

const musicProvider: {
  name: string
  value: string
  recommend?: boolean
}[] = [
    { name: '网易云', value: 'netease', recommend: true },
    { name: '酷我音乐', value: 'kuwo', recommend: true },
    { name: 'QQ音乐', value: 'tencent' },
    { name: '咪咕音乐', value: 'migu' },
    { name: '酷狗音乐', value: 'kugou' },
  ]

const Home = (): JSX.Element => {

  const cacheMusicProvider = useMemo(() => localStorage.getItem('cacheMusicProvider') || '', [])

  const [currentMusicProvider, setCurrentMusicProvider] = useState(
    musicProvider.find((provider) => provider.value === cacheMusicProvider) || musicProvider[0]
  )
  const [musicList, setMusicList] = useState<MusicStoreRecord[]>(JSON.parse(localStorage.getItem('cacheMusicList') || '[]'))
  const [keywords, setKeywords] = useState(localStorage.getItem('cacheSearchKeywords') || '')
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 30,
    total: 0
  })
  const [isError, setIsError] = useState(false)

  useEffect(() => {
    console.info('[render Page]:%c Home', 'color: red;', Date.now())
  })

  useEffect(() => {
    if (musicList.length > 0) {
      localStorage.setItem('cacheMusicList', JSON.stringify(musicList))
    }
  }, [musicList])

  /**
   * 请求实例
   * @data 歌曲列表
   * @loading 歌曲列表加载状态
   * @send 发送请求
   */
  const getMusicListRequest = useWatcher(() => {
    const params = {
      name: keywords,
      source: currentMusicProvider.value,
      count: pagination.pageSize,
      pages: pagination.current,
      types: 'search',
    }
    const methodIncetance = createAlovaMethod({
      api,
      params: params,
      name: 'getMusicList',
      // 进程间共享缓存适配器
      cacheFor: {
        // 缓存 'memory' | 'restore'
        mode: 'restore',
        // Cache time
        expire: 1000 * 60 * 120,
      },
    })
    methodIncetance.key = `getMusicList-${params.source}-${params.name}-${params.pages}-${params.count}`
    return methodIncetance
  }, [pagination, keywords], {
    initialData: [],
    immediate: false,
  })

  getMusicListRequest.onSuccess((res) => {
    const cacheSearchKeywords = localStorage.getItem('cacheSearchKeywords') || ''
    if (res.data && Array.isArray(res.data)) {
      if (keywords !== cacheSearchKeywords || pagination.current === 1) {
        localStorage.setItem('cacheSearchKeywords', keywords)
        setMusicList(res.data)
      } else {
        setMusicList(prevMusicList => {
          return [...new Set([...prevMusicList, ...res.data])]
        })
      }
    } else {
      setMusicList([])
    }
    localStorage.setItem('cacheSearchKeywords', keywords)
  }).onError(() => {
    console.error('error')
    setMusicList([])
  })

  /**
   * 搜索歌曲
   * @param keywords 搜索关键词
   * @returns 返回歌曲列表
   */
  const onSearch = (keywords: string): void => {
    if (!keywords) {
      toast.warning('请输入搜索内容')
      return
    }
    setKeywords(keywords)
    setPagination({
      ...pagination,
      current: 1,
    })
  }

  /**
   * 无限滚动加载
   */
  const InfiniteComponent = useMemo(() => {
    return <div className='flex justify-center py-6'>
      {getMusicListRequest.loading ? <Loading className='h-10' description='加载中...' /> : <>
        {musicList.length === 0 && <Empty description='请输入关键词搜索' />}
        {musicList.length === 0 && isError && pagination.current === 1 && <Empty description='没有找到相关音乐，请尝试其他关键词' />}
        {musicList.length > 0 && <Button variant='link' onClick={() => setPagination({ ...pagination, current: pagination.current + 1 })}>加载更多</Button>}
      </>}
    </div>
  }, [musicList, getMusicListRequest.loading])

  return <div className='home-page'>
    <div className='home-wrapper'>
      <div className='home-header'>
        <SearchBar onSearch={onSearch} />
        <Select
          defaultValue={currentMusicProvider.value}
          onValueChange={(value) => {
            localStorage.setItem('cacheMusicProvider', value)
            setCurrentMusicProvider(musicProvider.find((provider) => provider.value === value)!)
          }}
        >
          <SelectTrigger className="min-w-40">
            <SelectValue placeholder="选择音乐源" />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              {musicProvider.map((source) => {
                return <SelectItem
                  value={source.value}
                  key={source.value}
                >{source.name}{source.recommend && <span className='text-xs text-gray-500'>(推荐)</span>}</SelectItem>
              })}
            </SelectGroup>
          </SelectContent>
        </Select>
      </div>
      <div className='music-list-wrapper'>
        <MusicList
          musicList={musicList}
          isError={false}
          infiniteComponent={InfiniteComponent}
        />
      </div>
    </div>
  </div>

}

export default Home
